package com.atguigu.controller;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.result.R;
import com.atguigu.common.utils.JwtHelper;
import com.atguigu.config.ConstantPropertiesUtil;
import com.atguigu.config.HttpClientUtils;
import com.atguigu.service.UserInfoService;
import com.atguigu.yygh.model.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
    @Autowired
    private UserInfoService  userInfoService;
    @GetMapping("/getLoginParam")
    @ResponseBody
    public R getLoginParam() throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();
        map.put("self_redirect",true);
        map.put("id","weixinLogin");
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("scope","snsapi_login");
        map.put("redirect_uri", URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,"utf-8"));
        String state = System.currentTimeMillis()+"";
        map.put("state",state);//二维码
//        session.setAttribute("state",state);
        map.put("style","black");
        map.put("href","");
        return R.ok().data(map);
    }
    //回调接口  目的查询微信用户是否存在
    @GetMapping("callback")
    public   String callBack(String code) throws Exception {
        //获取临时票据
        System.out.println("临时票据"+code);
        //调用微信接口  根据 code来查询当前微信用户的openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +ConstantPropertiesUtil.WX_OPEN_APP_ID +
                "&secret=" +ConstantPropertiesUtil.WX_OPEN_APP_SECRET+
                "&code=" +code+
                "&grant_type=authorization_code";
        //调用工具类来发请求
        String s = HttpClientUtils.get(url);
        //将该字符串转换为json形式
        JSONObject jsonObject = JSONObject.parseObject(s);
        //来查询微信昵称
        String access_token = jsonObject.getString("access_token");
        //查询微信昵称时候 使用
        String openid = jsonObject.getString("openid");
        //3从userInfo表中查询微信用户
        UserInfo userInfo= userInfoService.selecwxByOpenId(openid);
        //4、微信用户在userinfo表中不存在，自动注册
        //自动注册 需要 openid 和nickname
       if(userInfo==null){
           //5、调用微信端接口，根据openid获取微信用户昵称
           String url_nick = "https://api.weixin.qq.com/sns/userinfo?" +
                   "access_token=" + access_token +
                   "&openid=" + openid;
           //工具类
           String result = HttpClientUtils.get(url_nick);
           //转换为json
           JSONObject jsonObject1 = JSONObject.parseObject(result);
           String nickname = jsonObject1.getString("nickname");

           userInfo=new UserInfo();
           userInfo.setOpenid(openid);
           userInfo.setNickName(nickname);//获取微信昵称
           userInfoService.save(userInfo);
       }
        String name = userInfo.getName();
       if(StringUtils.isEmpty(name)){
           name=userInfo.getNickName();
           if(StringUtils.isEmpty(name)){
               name=userInfo.getPhone();
           }
       }
       //设置令牌
        String token = JwtHelper.createToken(userInfo.getId(), name);
       //当前用户是否需要绑定手机号
         String phone=  userInfo.getPhone();
         if(phone==null){
             //需要绑定手机号
         }else{
             //不需要绑定
         }
        return "redirect:http://localhost:3000/weixin/callback?" +
                "name="+URLEncoder.encode(name,"utf-8")+"&" +
                "token="+token+"&" +
                "openid="+(StringUtils.isEmpty(userInfo.getPhone())?openid:"");// pages/weixin/callback.vue

    }
}
